package com.tanhua.api.impl.db;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.api.db.SoulReportApi;
import com.tanhua.domain.db.SoulReport;
import com.tanhua.mapper.db.SoulReportMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Richard Wang
 * @date 2021/9/5 20:09
 */
@Service
public class SoulReportApiImpl implements SoulReportApi {

    @Autowired
    private SoulReportMapper soulReportMapper;

    @Override
    public String findReportId(Long userId, Integer paperId, Integer standardId, Integer score) {
        //查找当前用户的报告
        QueryWrapper<SoulReport> qr = new QueryWrapper<>();
        qr.eq("user_id", userId);
        qr.eq("paper_id", paperId);
        SoulReport soulReport = soulReportMapper.selectOne(qr);
        //若之前有,则删除旧的
        if(soulReport!=null){
            soulReportMapper.deleteById(soulReport.getId());
        }
        //新增报告
        soulReport = insertReport(userId, paperId, standardId, score);
        return soulReport.getId().toString();
    }

    //抽取的新增报告的工具类
    private SoulReport insertReport(Long userId, Integer paperId, Integer standardId, Integer score) {
        SoulReport soulReport = new SoulReport();
        soulReport.setUserId(userId.intValue());
        soulReport.setPaperId(paperId);
        soulReport.setStandardId(standardId);
        soulReport.setScore(score);
        soulReportMapper.insert(soulReport);
        return soulReport;
    }


    @Override
    public SoulReport findReport(Integer reportId) {
        SoulReport soulReport = soulReportMapper.selectById(reportId);
        return soulReport;
    }

    @Override
    public String getReportId(Long userId, String reportId) {
        //查找当前用户的报告
        QueryWrapper<SoulReport> qr = new QueryWrapper<>();
        qr.eq("user_id", userId);
        qr.eq("paper_id",Integer.parseInt(reportId) );
        SoulReport soulReport = soulReportMapper.selectOne(qr);
        if (soulReport==null){
            return null;
        }
        return soulReport.getId().toString();
    }
}
